package com.nbcio.cd.controller;

import com.nbcio.cd.domain.CdUserStorage;
import com.nbcio.cd.service.ICdUserStorageService;
import com.nbcio.common.core.domain.R;
import com.nbcio.common.satoken.utils.LoginHelper;
import com.nbcio.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 云网盘存储管理Controller
 *
 * @author nbacheng
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/cd/storage")
public class CdStorageController {

    private final ICdUserStorageService cdUserStorageService;
    private final ISysUserService sysUserService;

    /**
     * 获取当前用户的存储统计
     */
    @GetMapping
    public R<CdUserStorage> getUserStorage() {
        try {
            Long userId = LoginHelper.getUserId();
            CdUserStorage userStorage = cdUserStorageService.getUserStorage(userId);
            return R.ok(userStorage);
        } catch (Exception e) {
            log.error("获取用户存储统计失败: {}", e.getMessage(), e);
            return R.fail("获取用户存储统计失败: " + e.getMessage());
        }
    }

    /**
     * 同步用户存储统计（根据实际文件数据重新计算）
     */
    @PostMapping("/sync")
    public R<CdUserStorage> syncUserStorage() {
        try {
            Long userId = LoginHelper.getUserId();
            CdUserStorage userStorage = cdUserStorageService.syncUserStorage(userId);
            log.info("用户存储统计同步成功: userId={}, usedSize={}, fileCount={}, folderCount={}", 
                userId, userStorage.getUsedSize(), userStorage.getFileCount(), userStorage.getFolderCount());
            return R.ok(userStorage);
        } catch (Exception e) {
            log.error("同步用户存储统计失败: {}", e.getMessage(), e);
            return R.fail("同步用户存储统计失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取所有用户的存储统计（管理员功能）
     */
    @GetMapping("/admin/list")
    public R<java.util.Map<String, Object>> getAllUserStorage() {
        try {
            // 获取所有用户的存储统计
            java.util.List<CdUserStorage> allStorages = cdUserStorageService.list();
            
            // 计算总计数据
            long totalSize = allStorages.stream().mapToLong(CdUserStorage::getTotalSize).sum();
            long totalUsed = allStorages.stream().mapToLong(CdUserStorage::getUsedSize).sum();
            int totalFiles = allStorages.stream().mapToInt(CdUserStorage::getFileCount).sum();
            int totalFolders = allStorages.stream().mapToInt(CdUserStorage::getFolderCount).sum();
            
            // 创建总计统计对象
            CdUserStorage totalStats = new CdUserStorage();
            totalStats.setTotalSize(totalSize);
            totalStats.setUsedSize(totalUsed);
            totalStats.setFileCount(totalFiles);
            totalStats.setFolderCount(totalFolders);
            
            // 获取用户信息
            java.util.List<java.util.Map<String, Object>> userList = new java.util.ArrayList<>();
            for (CdUserStorage storage : allStorages) {
                java.util.Map<String, Object> userMap = new java.util.HashMap<>();
                userMap.put("userId", storage.getUserId());
                
                // 查询用户名
                try {
                    var userVo = sysUserService.selectUserById(storage.getUserId());
                    userMap.put("userName", userVo != null ? userVo.getNickName() : "用户" + storage.getUserId());
                } catch (Exception e) {
                    log.warn("获取用户信息失败: userId={}", storage.getUserId(), e);
                    userMap.put("userName", "用户" + storage.getUserId());
                }
                
                userMap.put("totalSize", storage.getTotalSize());
                userMap.put("usedSize", storage.getUsedSize());
                userMap.put("fileCount", storage.getFileCount());
                userMap.put("folderCount", storage.getFolderCount());
                userMap.put("lastCleanupTime", storage.getLastCleanupTime());
                userList.add(userMap);
            }
            
            java.util.Map<String, Object> result = new java.util.HashMap<>();
            result.put("stats", totalStats);
            result.put("users", userList);
            
            return R.ok(result);
        } catch (Exception e) {
            log.error("获取所有用户存储统计失败: {}", e.getMessage(), e);
            return R.fail("获取所有用户存储统计失败: " + e.getMessage());
        }
    }
    
    /**
     * 管理员设置用户存储配额
     */
    @PostMapping("/admin/setQuota")
    public R<Void> setUserStorageQuota(@RequestParam Long userId, @RequestParam Long totalSize) {
        try {
            cdUserStorageService.setUserStorageQuota(userId, totalSize);
            log.info("管理员设置用户存储配额成功: userId={}, totalSize={}", userId, totalSize);
            return R.ok();
        } catch (Exception e) {
            log.error("设置用户存储配额失败: {}", e.getMessage(), e);
            return R.fail("设置用户存储配额失败: " + e.getMessage());
        }
    }
    
    /**
     * 管理员初始化用户存储统计
     */
    @PostMapping("/admin/initUserStorage")
    public R<Void> initUserStorage(@RequestParam Long userId) {
        try {
            cdUserStorageService.initUserStorage(userId);
            log.info("管理员初始化用户存储统计成功: userId={}", userId);
            return R.ok();
        } catch (Exception e) {
            log.error("初始化用户存储统计失败: {}", e.getMessage(), e);
            return R.fail("初始化用户存储统计失败: " + e.getMessage());
        }
    }
}
